<?php

/* Functions */
// We keep the functions in a seperate file so that any changes made will not modify your design

if(!function_exists('prettyErrorPrint'))
{
	/**
	 * Echo out error messages in the same format, you can modify this to make it look how you want. 
	 * Just echo whatever HTML in the function
	 *
	 * @param string $message The actual error message to display
	 */
	function prettyErrorPrint($message)
	{
		echo "<p>{$message}</p><p><a href=\"javascript:history.back()\">Go Back</a></p>";
		exit;
	}
}

/**
 * When we want to end the script due to an error call this, and then do what the options have set
 * Saves checking the constant multiple times in the script
 *
 * @param string $message The error message that should be displayed
 * @param mixed $redirect The constant to check in the options
 */
function triggerFail($message, $redirect=false)
{
	if(!$redirect)
	{
		prettyErrorPrint($message);
	}
	else 
	{
		header('Location: '.$redirect);
		exit;
	}
}
function getHeaders($url)
{
	// cURL to the URL and grab the headers created
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_NOBODY, 1);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_TIMEOUT, 5);
	$output = curl_exec($ch);
	curl_close($ch);
	
	// Now we have the headers, split them into an array
	return $split = explode("\n", $output);
}

function getURL($curlhead)
{
	$header = array(); // Once we've cleaned it all up this is where we'll store the header info
	$header['status'] = trim($curlhead[0]); // Since the first result is going to be the status code, store it
	
	// For the rest loop around each line
	for($i = 1; $i < count($curlhead); $i++)
	{
		// Let's trim the line (since there will be line breaks on the end)
		$j = trim($curlhead[$i]);
		
		// Now if it isn't a blank line let's check it out
		if($j != '')
		{
			// Split the line in two, and use the first split as the key and the second as the value
			preg_match('/^(.*): (.*)$/', $j, $matches);
			$header[trim($matches[1])] = trim($matches[2]);
		}
	}
	
	// Now we have $header containing the header contents.
	// If Location is set then it means this is a redirect and we can return it
	if(isset($header['Location']))
	{
		$urlParsed = parse_url($header['Location']); // Parse the URL
		// If no scheme is set, then we're going to assume they forgot the http and add it on and then reparse it
		if(!isset($urlParsed['scheme']))
		{
			$header['Location'] = RDTI_DEFAULT_SCHEME.$header['Location'];
		}
		
		// However if we're going to examine indepth then we should check this new location
		return $header['Location'];
	}
	
	// If Location isn't set then just return false
	else
		return false;
}

function checkURL($url)
{
	$loopcount = RDTI_DEPTH;
	$i = 1;
	$run = $url;
		
	while($run && $i < $loopcount)
	{
		$head = getHeaders($url);
		$run = getURL($head);
		
		if($run)
		{
			$url = $run;
		}
		$i++;
	}
	
	return $url;
}
?>